package com.cj.sys.dao.security;

import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;

import org.springframework.stereotype.Repository;

import com.cj.common.orm.hibernate.HibernateDao;
import com.cj.common.security.springsecurity.SpringSecurityUtils;
import com.cj.sys.entity.security.Authority;
import com.cj.sys.entity.security.Resource;
import com.cj.sys.entity.security.User;
import com.cj.sys.service.ServiceException;

/**
 * 用户泛型DAO类.
 * 
 * @author calvin
 */
@Repository
public class UserDao extends HibernateDao<User, Long> {
	/**
	 * 【返回当前用户】
	 * 
	 * @return
	 * @author:cj [2009-7-6 下午08:26:08]
	 */
	public User getCurrentUser() {
		return super.findByUnique("code", SpringSecurityUtils
				.getCurrentUserName());
	}
	@Override
	public void save(User entity) {
		if(entity.getDept() != null)
			entity.setFullName(entity.getName());
		if(entity.getDept() != null && entity.getDept().getId() == null)
			entity.setDept(null);
		
		if(entity.getId() == null)
			entity.setCreatTime(new Date());
		entity.setLastModifyTime(new Date());
		if(isPropertyUniqueById("code", entity.getCode(), entity.getId()))
			super.save(entity);
		else
			throw new ServiceException("用户登录名已存在！");
	}
	
	public Set<Resource> getResources(Long userId){
		Set<Resource> resources = new LinkedHashSet<Resource>();
		User user = this.load(userId);
		for(Authority authority : user.getAuthorities()){
			for(Resource resource:authority.getResources()){
				if(Resource.MENU_TYPE.equalsIgnoreCase(resource.getResourceType()))
					resources.add(resource);
			}
		}
		return resources;
	}
}
